function quickViewTrace(varargin)
% quickViewTrace
%
% Use this to look at ephus/xsg traces
%
% Notes:
% - trace data sent to 'currentTrace' variable in the workspace

% TODO:
% add buttons to dump headers for mapper, stimulator, acquirer, etc

% editing:
% gs jan 2006, april-may 2006, dec 2006, jan 2007
% ---------------------------------------------------
if nargin == 0
    mode = 'init';
else 
    mode = varargin{1};
end

% preferred default directory
defaultDirectory = 'C:\_Data2\Gordon';

switch mode
    case 'init'
        % select a trace to open
        try
            cd(defaultDirectory);
        catch
            try
                cd('C:\_Data');
            catch
                try
                    cd('C:\_DATA');
                catch
                    try
                        cd('C:\DATA');
                    catch
                    end
                end
            end
        end
        [filename, pathname] = uigetfile('*.xsg', 'Select an XSG trace');
        % if filename == 0 | pathname == 0
        if isequal(filename,0)|isequal(pathname,0)
            return
        end
        fullfilename = fullfile(pathname, filename);
        [pathstr, tracename, ext, versn] = fileparts(fullfilename);
        data.completename = fullfile(pathstr, [tracename, ext, versn]);
        
        hfig = figure(1000);
%         data = get(gcf, 'UserData');
        % store the file and directory info
        set(hfig, 'UserData', data.completename);
        
%         clf;
        % figure
        set(hfig, 'Color', 'w', 'Name', 'quickViewTrace', 'NumberTitle', 'off');

    case 'select new file'
        hfig = figure(1000);
        data = get(gcf, 'UserData');
        saveCurrentDirectory = pwd;
        [pathstr, tracename, ext, versn] = fileparts(data.completename);
        cd(pathstr);
        % select a trace to open
        [filename, pathname] = uigetfile('*.xsg', 'Select an XSG trace');
        % if filename == 0 | pathname == 0
        if isequal(filename,0)|isequal(pathname,0)
            return
        end
        fullfilename = fullfile(pathname, filename);
        [pathstr, tracename, ext, versn] = fileparts(fullfilename);
        data.completename = fullfile(pathstr, [tracename, ext, versn]);
        cd(saveCurrentDirectory)
        
        % figure
        hfig = figure(1000);
        data = get(gcf, 'UserData');
        clf;
        set(hfig, 'Color', 'w', 'Name', 'quickViewTrace', 'NumberTitle', 'off');
        % store the file and directory info
        set(hfig, 'UserData', data.completename);
                
    case 'scroll backwards'
        hfig = figure(1000);
        data = get(gcf, 'UserData');
        clf;
        set(hfig, 'Color', 'w', 'Name', 'quickViewTrace', 'NumberTitle', 'off');
        [pathstr, tracename, ext, versn] = fileparts(data.completename);
        fullfile(pathstr, ['*' ext]);
        traceFiles = dir(fullfile(pathstr, ['*' ext]));
        c = struct2cell(traceFiles);
        list = char(c{1,:});
        k = strmatch(tracename, list);
        if k > 1
            newfilename = list(k-1,:); % file name of the preceding (k-1) file
            data.completename = fullfile(pathstr, newfilename);
            [pathstr, tracename, ext, versn] = fileparts(data.completename);
        end
        
        % store the file and directory info
        set(hfig, 'UserData', data);
        
    case 'scroll forwards'
        hfig = figure(1000);
        data = get(gcf, 'UserData');
        clf;
        set(hfig, 'Color', 'w', 'Name', 'quickViewTrace', 'NumberTitle', 'off');
        [pathstr, tracename, ext, versn] = fileparts(data.completename);
        fullfile(pathstr, ['*' ext]);
        traceFiles = dir(fullfile(pathstr, ['*' ext]));
        c = struct2cell(traceFiles);
        list = char(c{1,:});
        k = strmatch(tracename, list);
        if k < size(list, 1)
            newfilename = list(k+1,:); % file name of the following (k+1) file
            data.completename = fullfile(pathstr, newfilename);
            [pathstr, tracename, ext, versn] = fileparts(data.completename);
        end
        
        % store the file and directory info
        set(hfig, 'UserData', data);
        
    case 'header to command line'
        hfig = figure(1000);
        data = get(gcf, 'UserData');
        eval('data.currentTrace.header.ephys.ephys');
        return
end

% open the file, extract the data
currentTrace = load(data.completename, '-mat'); 

% put the data in the workspace
assignin('base', 'currentTrace', currentTrace);

% store in figure's userData
data.currentTrace = currentTrace;
set(hfig, 'UserData', data);

% sort out what kind of data there are
dataSources = fieldnames(currentTrace.data);
numSources = size(dataSources, 1);

if any(strcmp('ephys', dataSources))
    if ~isempty(currentTrace.data.ephys)
        dataSourcesEphys = fieldnames(currentTrace.data.ephys);
        numDataSourcesEphys = size(dataSourcesEphys, 1);
    else
        numDataSourcesEphys = 0;
    end
end
if any(strcmp('acquirer', dataSources))
    if ~isempty(currentTrace.data.acquirer)
        dataSourcesAcquirer = fieldnames(currentTrace.data.acquirer);
        numDataSourcesAcquirer = size(dataSourcesAcquirer, 1);
    else
        numDataSourcesAcquirer = 0;
    end
end
    
% TODO: make the following ephys plot conditional, to handle
% case of no ephys data
%
% plot ephys data
str = ['currentTrace.data.ephys.' dataSourcesEphys{1}]; 
ephysdata = eval(str);
timedata = 0 : size(ephysdata, 1) - 1;
sr = currentTrace.header.ephys.ephys.sampleRate;
timedata = timedata / sr;
hax1 = axes;

plot(timedata, ephysdata);
set(hax1, 'XTickLabel', [], 'Units', 'normalized', ...
    'Position', [0.1300    0.400    0.7750    0.5150]);
% xlabel('Samples');
% xlabel('Time (seconds)');
ylabel('Amplitude');
htitle = title([pathstr '\' tracename]);
set(htitle, 'Interpreter', 'none');
box off;

% plot pulse
% extract pulse info
pulseNumber = str2num(currentTrace.header.ephys.ephys.pulseNumber);
% params = currentTrace.header.ephys.ephys.TEMP_PulseParameters{pulseNumber};
params = currentTrace.header.ephys.ephys.TEMP_PulseParameters{1};
pulsedata = zeros * ephysdata; % make a template based on the trace
pulsedata = pulsedata + params.offset;
sr = params.sampleRate;
delayInd = params.squarePulseTrainDelay * sr + 1;
% note: add 1 because first sample is at time 0
durInd = params.squarePulseTrainWidth * sr;
isiInd = params.squarePulseTrainISI * sr;
try
    if params.squarePulseTrainNumber == 1
        pulsedata(delayInd : delayInd + durInd) = ...
            pulsedata(delayInd : delayInd + durInd) + params.amplitude;
        %     'yo'
    elseif params.squarePulseTrainNumber > 1
        %         disp('quickViewTrace: multiple steps not yet implemented');
        for n = 0 : params.squarePulseTrainNumber - 1
            try
                startInd = delayInd + n * isiInd;
                endInd = startInd + durInd;

                if endInd <= size(pulsedata, 1)
                    % normal step
                    pulsedata(startInd : endInd) = ...
                        pulsedata(startInd : endInd) + params.amplitude;

                elseif endInd > size(pulsedata, 1)
                    
                    if startInd <= size(pulsedata, 1)
                        % truncated step in trace -- fill in to end
                        pulsedata(startInd : end) = ...
                            pulsedata(startInd : end) + params.amplitude;

                    elseif startInd > size(pulsedata, 1)
                        % no step in trace -- nothing to do
                        
                    end
                end
            catch
                'problem'
            end
        end
    end
catch
    'quickViewTrace: problem making pulse'
end

hax2 = axes;
hplt = plot(timedata, pulsedata);
set(hplt, 'LineWidth', 2, 'Color', 'r');
set(hax2, 'Units', 'normalized', ...
    'Position', [0.1300    0.09    0.7750    0.120]);
yl = ylim;
yrange = yl(2) - yl(1);
ylim([(yl(1) - 0.05 * yrange) (yl(2) + 0.05 * yrange)]);
% xlabel('Samples');
xlabel('Time (seconds)');
ylabel('Amplitude');
% htitle = title([pathstr '\' tracename]);
% set(htitle, 'Interpreter', 'none');
htitle = title(['Pulse: ' params.name]);
set(htitle, 'Interpreter', 'none');
box off;


% ========= under development: start ========================
% plot acquirer trace; i.e., photodiode signal
if numDataSourcesAcquirer > 0  
    % plot acquirer data
    str = ['currentTrace.data.acquirer.' dataSourcesAcquirer{1}];
    acquirerdata = eval(str);
    timedata = 0 : size(acquirerdata, 1) - 1;
    sr = currentTrace.header.acquirer.acquirer.sampleRate;
    timedata = timedata / sr;
    hax1 = axes;

    plot(timedata, acquirerdata);
    set(hax1, 'XTickLabel', [], 'Units', 'normalized', ...
        'Position', [0.1300    0.400    0.7750    0.5150]);
    % xlabel('Samples');
    % xlabel('Time (seconds)');
    ylabel('Amplitude');
    htitle = title([pathstr '\' tracename]);
    set(htitle, 'Interpreter', 'none');
    box off;
end
% ========= under development: end ========================




% plot pockels pulse (and mechanical shutter pulse)

% uicontrols -- sliders to scroll through traces
hscrollerbackwards = uicontrol('Style', 'pushbutton', 'String', '<<', ...
    'Units', 'normalized', ...
    'Position', [.92 .93 .04 .07], 'Callback', 'quickViewTrace(''scroll backwards'')');

hscrollerforwards = uicontrol('Style', 'pushbutton', 'String', '>>', ...
    'Units', 'normalized', ...
    'Position', [.96 .93 .04 .07], 'Callback', 'quickViewTrace(''scroll forwards'')');

% uicontrol -- pushbutton to select new file/directory
hselectnewfile = uicontrol('Style', 'pushbutton', 'String', 'New', ...
    'Units', 'normalized', ...
    'Position', [.92 .86 .08 .07], 'Callback', 'quickViewTrace(''select new file'')');

% uicontrol -- pushbutton to print header to command line
hheaderprint = uicontrol('Style', 'pushbutton', 'String', 'Header', ...
    'Units', 'normalized', ...
    'Position', [.92 .79 .08 .07], 'Callback', 'quickViewTrace(''header to command line'')');

% something to show epoch